# -*- coding: utf8 -*-
from django.conf import settings
from django.contrib import auth
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_POST
from bootcamp.decorators import ajax_required
from registration.users import UserModel
from django.contrib.auth.models import User
from bootcamp.feeds.models import Feed
from django.core.context_processors import csrf
from django.template.loader import render_to_string
from django.shortcuts import render, redirect, get_object_or_404
import random
import json

FEEDS_NUM_PAGES = 20

MAJOR_VERSION = 0
MID_VERSION = 1
MIN_VERSION = 3
NOTE = """
更新内容：
1. 删除评论、帖子，取消赞扣分以防刷经验；
2. 增加修改资料功能；
"""
URL = "http://nqzx.net/media/ads/nqzx.apk"

def check_version(version):
    ret = False
    ls = version.split('.')
    if MAJOR_VERSION > int(ls[0]):
        ret = True
    elif MID_VERSION > int(ls[1]):
        ret = True
    elif MIN_VERSION > int(ls[2]):
        ret = True
    else:
        ret = False
    return ret

def get_level(reputation):
    if not reputation:
        return 1;
    if reputation < 5:
        return 1
    elif reputation < 15:
        return 2
    elif reputation < 30:
        return 3
    elif reputation < 50:
        return 4
    elif reputation < 100:
        return 5
    elif reputation < 200:
        return 6
    elif reputation < 500:
        return 7
    elif reputation < 1000:
        return 8
    elif reputation < 2000:
        return 9
    elif reputation < 3000:
        return 10
    elif reputation < 6000:
        return 11
    elif reputation < 10000:
        return 12
    elif reputation < 18000:
        return 13
    elif reputation < 30000:
        return 14
    elif reputation < 60000:
        return 15
    elif reputation < 100000:
        return 16
    elif reputation < 300000:
        return 17
    else:
        return 18

@require_POST
@ajax_required
def login(request):
    username = request.POST.get('account')
    password = request.POST.get('password')
    result = {"status": False, "data":""}
    if not username or not password:
        result = {"status": False, "data":"未收到用户名或密码！"}
        return HttpResponse(json.dumps(result), content_type="application/json")
    if username=="" or username.isspace():
        result = {"status": False, "data":"用户名不能为空"}
        return HttpResponse(json.dumps(result), content_type="application/json")
    if password=="" or password.isspace():
        result = {"status": False, "data":"密码不能为空"}
        return HttpResponse(json.dumps(result), content_type="application/json")
    user = auth.authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            auth.login(request, user)
            result = {"status": True, "data": {"id": user.id, "email": user.email, \
                "location": user.profile.location, "mobile": user.profile.mobile, "reputation": \
                user.profile.reputation,"signdate": user.profile.signdate}}
        else:
            result = {"status": False, "data":"["+username+"]已被暂时禁用"}
    else:
        result = {"status": False, "data":"用户名或密码不正确，请重试"}
    return HttpResponse(json.dumps(result), content_type="application/json")

@require_POST
@ajax_required
def reg(request):
    username = request.POST.get('account')
    password = request.POST.get('password')
    email = request.POST.get('email')
    result = {"status": False, "data":""}
    if not username or not password or not email:
        result = {"status": False, "data":"未收到用户名、密码或者用户名！"}
        return HttpResponse(json.dumps(result), content_type="application/json")
    if username=="" or username.isspace():
        result = {"status": False, "data":"用户名不能为空"}
        return HttpResponse(json.dumps(result), content_type="application/json")
    if password=="" or password.isspace():
        result = {"status": False, "data":"密码不能为空"}
        return HttpResponse(json.dumps(result), content_type="application/json")
    if email=="" or email.isspace():
        result = {"status": False, "data":"邮箱不能为空"}
        return HttpResponse(json.dumps(result), content_type="application/json")
    # clean data
    existing = UserModel().objects.filter(username__iexact=username)
    if existing.exists():
        result = {"status": False, "data":"用户名已经存在"}
        return HttpResponse(json.dumps(result), content_type="application/json")
    if UserModel().objects.filter(email__iexact=email):
        result = {"status": False, "data":"邮箱已经存在"}
        return HttpResponse(json.dumps(result), content_type="application/json")

    user = UserModel().objects.create_user(username, email, password)
    user.is_active = True
    user.save()
    result = {"status": True, "data": {"id": user.id, "email": user.email, \
        "location": user.profile.location, "mobile": user.profile.mobile, "reputation": \
        user.profile.reputation,"signdate": user.profile.signdate}}
    return HttpResponse(json.dumps(result), content_type="application/json")

@require_POST
@ajax_required
def get_state(request):
    user = request.user
    state = {"id": user.id, "username": user.username, "email": user.email, "location": user.profile.location, \
            "mobile": user.profile.mobile, "reputation": user.profile.reputation,"first_name": user.first_name, \
            "sex": user.profile.sex,"signdate": user.profile.signdate}
    return HttpResponse(json.dumps(state), content_type="application/json")

@require_POST
@ajax_required
def set_state(request):
    result = {"status": False, "data": {}}
    userid = request.POST.get('userid')
    user = User.objects.get(pk=userid)
    if not user:
        return HttpResponse(json.dumps(state), content_type="application/json")
    first_name = request.POST.get('first_name')
    location = request.POST.get('location')
    mobile = request.POST.get('mobile')
    reputation = request.POST.get('reputation')
    sex = request.POST.get('sex')
    signdate = request.POST.get('signdate')
    if first_name:
        user.first_name = first_name;
    if location:
        user.profile.location = location
    if mobile:
        user.profile.mobile = mobile
    if reputation:
        user.profile.reputation = reputation
    if sex:
        user.profile.sex = sex
    if signdate:
        user.profile.signdate = signdate
    user.save()
    result = {"status": True, "data": {"first_name": first_name, "sex": sex, \
                "location":location,"mobile":mobile,"reputation":reputation,"signdate":signdate}}
    return HttpResponse(json.dumps(result), content_type="application/json")

def get_feeds(request):
    page = 1
    feed_id = request.POST["feed_id"]
    csrf_token = unicode(csrf(request)['csrf_token'])
    html = u''
    if feed_id:
        feed = Feed.objects.get(pk=feed_id)
        html = u'{0}{1}'.format(html, render_to_string('app/partial_feed.html', {
            'feed': feed,
            'user': request.user,
            'csrf_token': csrf_token,
            'lvl': get_level(feed.user.profile.reputation),
            })
        )
    else:
        feeds = Feed.get_feeds()
        paginator = Paginator(feeds, FEEDS_NUM_PAGES)
        feeds = paginator.page(page)
        for feed in feeds:
            html = u'{0}{1}'.format(html, render_to_string('app/partial_feed.html', {
                'feed': feed,
                'user': request.user,
                'csrf_token': csrf_token,
                'lvl': get_level(feed.user.profile.reputation),
                })
            )
    return HttpResponse(html)

@ajax_required
def checkupdate(request):
    version = request.POST.get('version')
    ret = {"status": check_version(version), "note": NOTE, "url": URL}
    return HttpResponse(json.dumps(ret), content_type="application/json")

def _html_feeds(last_feed, user, csrf_token, feed_source='all'):
    feeds = Feed.get_feeds_after(last_feed)
    if feed_source != 'all':
        feeds = feeds.filter(user__id=feed_source)
    html = u''
    for feed in feeds:
        html = u'{0}{1}'.format(html, render_to_string('app/partial_feed.html', {
            'feed': feed,
            'user': user,
            'csrf_token': csrf_token,
            'lvl': get_level(feed.user.profile.reputation),
            })
        )
    return html

def post(request):
    last_feed = request.POST.get('last_feed')
    user = request.user
    rand_user = User.objects.get(pk=random.randint(318, 367))
    csrf_token = unicode(csrf(request)['csrf_token'])
    feed = Feed()
    if user.id == 283:
        feed.user = rand_user
    else:
        feed.user = user
    post = request.POST['post']
    post = post.strip()
    if len(post) > 0:
        feed.post = post[:255]
        user.profile.reputation += 3
        user.save()
        feed.save()
    html = _html_feeds(last_feed, user, csrf_token)
    return HttpResponse(html)

def load(request):
    from_feed = request.GET.get('from_feed')
    page = request.GET.get('page')
    active = request.GET.get('active')
    feed_source = request.GET.get('feed_source')
    if active and active != 'all':
        all_feeds = Feed.get_feeds(from_feed, active)
    else:
        all_feeds = Feed.get_feeds(from_feed)
    if feed_source != 'all':
        all_feeds = all_feeds.filter(user__id=feed_source)
    paginator = Paginator(all_feeds, FEEDS_NUM_PAGES)
    try:
        feeds = paginator.page(page)
    except EmptyPage:
        feeds = []
    html = u''
    csrf_token = unicode(csrf(request)['csrf_token'])
    for feed in feeds:
        html = u'{0}{1}'.format(html, render_to_string('app/partial_feed.html', {
            'feed': feed,
            'user': request.user,
            'lvl': get_level(feed.user.profile.reputation),
            'csrf_token': csrf_token
            })
        )
    return HttpResponse(html)

def load_new(request):
    last_feed = request.GET.get('last_feed')
    user = request.user
    csrf_token = unicode(csrf(request)['csrf_token'])
    html = _html_feeds(last_feed, user, csrf_token)
    return HttpResponse(html)

def comment(request):
    if request.method == 'POST':
        feed_id = request.POST['feed']
        feed = Feed.objects.get(pk=feed_id)
        post = request.POST['post']
        post = post.strip()
        if len(post) > 0:
            post = post[:255]
            user = request.user
            feed.comment(user=user, post=post)
            user.profile.notify_commented(feed)
            user.profile.notify_also_commented(feed)
            user.profile.reputation += 2
            user.save()
        return render(request, 'app/partial_feed_comments.html', {'feed': feed})
    else:
        feed_id = request.GET.get('feed')
        feed = Feed.objects.get(pk=feed_id)
        return render(request, 'app/partial_feed_comments.html', {'feed': feed})

def track_comments(request):
    feed_id = request.GET.get('feed')
    feed = Feed.objects.get(pk=feed_id)
    return render(request, 'app/partial_feed_comments.html', {'feed': feed})
